#!/bin/sh
# PCP QA Test No. 780
# Exercise PMWEBAPI CORS headers.
#
# Copyright (c) 2014,2019-2020 Red Hat.
#

seq=`basename $0`
echo "QA output created by $seq"

# get standard environment, filters and checks
. ./common.product
. ./common.filter
. ./common.check

_check_series
which curl >/dev/null 2>&1 || _notrun "No curl binary installed"

status=1	# failure is the default!
trap "cd $here; _cleanup; exit \$status" 0 1 2 3 15

pmproxy_was_running=false
[ -f $PCP_RUN_DIR/pmproxy.pid ] && pmproxy_was_running=true
echo "pmproxy_was_running=$pmproxy_was_running" >>$seq_full

_cleanup()
{
    if $pmproxy_was_running
    then
	echo "Restart pmproxy ..." >>$seq_full
	_service pmproxy restart >>$seq_full 2>&1
	_wait_for_pmproxy
    else
	echo "Stopping pmproxy ..." >>$seq_full
	_service pmproxy stop >>$seq_full 2>&1
    fi
    $sudo rm -f $tmp.*
}

# real QA test starts here
if ! _service pmproxy restart >/dev/null 2>&1; then _exit 1; fi

echo "=== Basic" | tee -a $seq_full
curl -IsS "http://localhost:44323/pmapi/context" | _webapi_header_filter

echo "=== Preflight" | tee -a $seq_full
curl -isS -X OPTIONS "http://localhost:44323/series/query?expr=hinv*" | _webapi_header_filter

echo "=== OK Request Method" | tee -a $seq_full
curl -isS -X OPTIONS -H "Origin: http://example.com" -H "Access-Control-Request-Method: GET" "http://localhost:44323/pmapi/context" | _webapi_header_filter

echo "=== Bad Request Method" | tee -a $seq_full
curl -isS -X OPTIONS -H "Origin: http://example.com" -H "Access-Control-Request-Method: BAD" "http://localhost:44323/pmapi/context" | _webapi_header_filter

echo >>$seq_full
echo "=== pmproxy log ===" >>$seq_full
cat $PCP_LOG_DIR/pmproxy/pmproxy.log >>$seq_full

# success, all done
status=0
exit
